package io.nick.reqenhance.filter;

import org.springframework.util.StreamUtils;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @author Nick
 * @date 2019-08-11 13:25
 */
public class MuteRequestWrapper extends HttpServletRequestWrapper {

  // 报文
  //  private final byte[] body;

  private byte[] body;

  public MuteRequestWrapper(HttpServletRequest request) throws IOException {
    super(request);
    body = StreamUtils.copyToByteArray(request.getInputStream());
  }

  public void muteBuffer(byte[] mute) {
    body = mute;
  }

  //  /**
  //   * 流转 字节数组
  //   *
  //   * @param is 输入流
  //   * @return 字节数组
  //   */
  //  private byte[] inputStreamToByte(InputStream is) throws IOException {
  //    ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
  //    byte[] buffer = new byte[8192];
  //    int ch;
  //    while ((ch = is.read(buffer)) != -1) {
  //      bytestream.write(buffer, 0, ch);
  //    }
  //    byte[] data = bytestream.toByteArray();
  //    bytestream.close();
  //    return data;
  //  }

  @Override
  public BufferedReader getReader() {
    return new BufferedReader(new InputStreamReader(getInputStream()));
  }

  @Override
  public ServletInputStream getInputStream() {
    final ByteArrayInputStream bais = new ByteArrayInputStream(body);
    return new ServletInputStream() {

      @Override
      public boolean isFinished() {
        return false;
      }

      @Override
      public boolean isReady() {
        return false;
      }

      @Override
      public void setReadListener(ReadListener listener) {}

      @Override
      public int read() {
        return bais.read();
      }
    };
  }
}
